package com.buka.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buka.domain.ResponseResult;
import com.buka.dto.UserDto;
import com.buka.enums.AppHttpCodeEnum;
import com.buka.exception.SystemException;
import com.buka.mapper.UserMapper;
import com.buka.pojo.Role;
import com.buka.pojo.User;
import com.buka.pojo.UserRole;
import com.buka.service.RoleService;
import com.buka.service.UserRoleService;
import com.buka.service.UserService;
import com.buka.util.BeanCopyUtils;
import com.buka.util.SecurityUtils;
import com.buka.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 26755
 * @description 针对表【sys_user】的数据库操作Service实现
 * @createDate 2024-04-11 11:00:41
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 个人信息查询
     */
    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = getById(userId);
        //封装成UserInfoVo
        UserInfoVo vo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(vo);
    }

    /**
     * 更新个人信息
     */
    @Override
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }

    /**
     * 用户注册
     */
    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if (!StringUtils.hasText(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getPassword())) {
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getEmail())) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getNickName())) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if (userNameExist(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (nickNameExist(user.getNickName())) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存入数据库
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult list(int pageNum, int pageSize, String phonenumber, String status) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(phonenumber)) {
            userLambdaQueryWrapper.eq(User::getPhonenumber, phonenumber);
        }
        if (StringUtils.hasText(status)) {
            userLambdaQueryWrapper.eq(User::getStatus, status);
        }
        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> userPage = page(page, userLambdaQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("rows", userPage.getRecords());
        map.put("total", userPage.getTotal());
        return ResponseResult.okResult(map);
    }

    @Autowired
    private UserRoleService userRoleService;

    @Transactional
    @Override
    public ResponseResult add(UserDto userDto) {
        User user = BeanCopyUtils.copyBean(userDto, User.class);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);
        List<UserRole> userRoleList = new ArrayList<>();
        for (Integer roleId : userDto.getRoleIds()) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(Long.valueOf(roleId));
            userRole.setUserId(user.getId());
            userRoleList.add(userRole);
        }
        userRoleService.saveBatch(userRoleList);
        return ResponseResult.okResult();
    }

    @Autowired
    private RoleService roleService;

    @Override
    public ResponseResult get(int id) {
        Map<String, Object> result = new HashMap<>();
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(Role::getStatus, 0);
        List<Role> roleList = roleService.list(roleLambdaQueryWrapper);
        result.put("roles", roleList);
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUserId, id);
        List<UserRole> userRoleList = userRoleService.list(userRoleLambdaQueryWrapper);
        List<Integer> userRoleIds = userRoleList.stream().map(userRole -> userRole.getRoleId().intValue()).collect(Collectors.toList());
        result.put("roleIds", userRoleIds);
        User user = getById(id);
        result.put("user", user);
        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult update(UserDto userDto) {
        User user = BeanCopyUtils.copyBean(userDto, User.class);
        updateById(user);
        List<UserRole> userRoleList = userDto.getRoleIds().stream().map(integer -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(new Long(integer));
            userRole.setUserId(user.getId());
            return userRole;
        }).collect(Collectors.toList());
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUserId, user.getId());
        userRoleService.getBaseMapper().delete(userRoleLambdaQueryWrapper);
        userRoleService.saveBatch(userRoleList);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delete(int id) {
        getBaseMapper().deleteById(id);
        return ResponseResult.okResult();
    }

    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getNickName, nickName);
        return count(lambdaQueryWrapper) > 0;
    }


    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName, userName);
        return count(lambdaQueryWrapper) > 0;
    }

}




